package ufrj.safcp.tools.imageio;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageDiskManipulator {
	
	private static Logger logger = LoggerFactory.getLogger(ImageDiskManipulator.class);
	
	public static String tempDir = System.getProperty("java.io.tmpdir");
	
	public static File saveTemporaryImage(BufferedImage image) {
		return save(image, tempDir, "cartao_image", "jpg" );
	}
	
	public static File save(BufferedImage image, String dir, String fileName, String ext) {
        File file = new File(dir + File.separator + fileName + "." + ext);
        try {
            ImageIO.write(image, ext, file);  // ignore returned boolean
        } catch(IOException e) {
            logger.error("Write error for " + file.getPath() + ": " + e.getMessage());
        }
        return file;
    }
	
	public static BufferedImage load(URL url) {
		try {
			return load (new File(url.toURI()));
		} catch (URISyntaxException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}
	
	public static BufferedImage load(String dir, String fileName, String ext) {
        File file = new File(dir + File.separator + fileName + "." + ext);
        return load(file);
    }

	private static BufferedImage load(File file) {
		BufferedImage image;
        try {
			image = ImageIO.read(file);
        } catch(IOException e) {
            throw new IllegalStateException("Write error for " + file.getPath() + ": " + e.getMessage());
        }
        return image;
	}


}
